package com.support;

import com.exception.ConditionException;
import com.service.impl.UserServiceImpl;
import com.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Component
public class UserSupport {

    @Autowired
    private UserServiceImpl userServiceImpl;

    /**
     * 1.判断短时令牌是否合法，如果合法，走第2步；不合法，提示“非法用户”
     * 2.判断请求头里的长时令牌是否和数据库里的长时令牌相匹配，如果匹配，返回userId；否则提示 “非法用户”
     */
    public Long getCurrentUserId() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String token = requestAttributes.getRequest().getHeader("token");
        Long userId = TokenUtil.verifyToken(token);
        if (userId < 0) {
            throw new ConditionException("401", "非法用户");
        }
        //this.verifyRefreshToken(userId);
        return userId;
    }

    /**
     * 验证当前登录用户的长时令牌
     */
    private void verifyRefreshToken(Long userId) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String refreshToken = requestAttributes.getRequest().getHeader("refreshToken");
        String dbRefreshToken = userServiceImpl.getRefreshTokenByUserId(userId);
        if (!dbRefreshToken.equals(refreshToken)) {
            throw new ConditionException("401", "非法用户！");
        }
    }
}